﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BLL;
using IFactory;
using System.IO;

public partial class QuarterPlan_VerifyQuarterPlan : System.Web.UI.Page
{
    IBussinessLogic dllDepartment = new DepartmentInfoManager();
    IBussinessLogic dllUserInfo = new UserInfoManager();
    QuarterPlanDetailManager dllQuarterPlanDetail = new QuarterPlanDetailManager();
    QuarterPlanofManager dllQuarterPlanofManager = new QuarterPlanofManager();
    Authentication dllAuthentication = new Authentication();
    QuarterDateManager dllQuarterDateManager = new QuarterDateManager();
    Model.UserInfo objUserInfo = new Model.UserInfo();
    DataTable _powerTable = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        dllAuthentication.isLogin();
        this.gdvQuarterPlan.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");
        this.gdvQuarterPlan.Attributes.Add("style", "word-break:break-all;word-wrap:break-word");
        this.btnAttachmentPath.Enabled = false;
        this.btnReturn.Enabled = false;
        this.btnVerifyCircuit.Enabled = false;
        _powerTable = dllAuthentication.getPower(objUserInfo.UserName, "已发年计划");
        for (int i = 0; i < _powerTable.Rows.Count; i++)
        {
            if (_powerTable.Rows[i]["PowerName"].ToString() == "新建")
            {
                
            }
            if (_powerTable.Rows[i]["PowerName"].ToString() == "删除")
            {
            }
            if (_powerTable.Rows[i]["PowerName"].ToString() == "查看")
            {
                this.btnVerifyCircuit.Enabled = true;
            }
            if (_powerTable.Rows[i]["PowerName"].ToString() == "修改")
            {
                this.btnAttachmentPath.Enabled = true;
                this.btnReturn.Enabled = true;
            }
        }    
        if (!IsPostBack)
        {
            #region 弹出提醒
            PopupManager dllPopupManager = new PopupManager();
            string _info = dllPopupManager.getPopupInfo();
            if (_info.Length > 0)
            {
                ShowMessage(_info);
            }
            #endregion
            bindDropDownList(this.drpYear);
            bindDropDownList(this.drpDepartment);
            bindDropDownList(this.drpQuarterDate);
            bindQuarterPlan();
        }
    }

    /// <summary>
    /// 弹出小窗体事件
    /// </summary>
    /// <param name="msg"></param>
    public void ShowMessage(string msg)
    {
        EeekSoft.Web.PopupWin pop = new EeekSoft.Web.PopupWin();
        this.Controls.Add(pop);
        pop.Text = msg;
        pop.Message = msg;
        pop.Title = System.Configuration.ConfigurationManager.AppSettings["CompanyName"].ToString();
        pop.WindowScroll = true;
        pop.HideAfter = 99999999;
        pop.DockMode = EeekSoft.Web.PopupDocking.BottomLeft;
        pop.OffsetX = int.Parse(Session["_width"].ToString()) - 338;
        pop.ActionType = EeekSoft.Web.PopupAction.MessageWindow;
        pop.OffsetY = 1;
        pop.Width = 220;
        pop.Height = 170;
    }




    /// <summary>
    /// 根据逗号换行事件
    /// </summary>
    void wrapByComma(GridView _gridView, int _rowIndex, int _cells)
    {
        string _content = _gridView.Rows[_rowIndex].Cells[_cells].Text;
        _gridView.Rows[_rowIndex].Cells[_cells].Text = _content.Replace("&lt;br&gt;", "<br>");
        //_gridView.Rows[_rowIndex].Cells[_cells].Text = _content.Replace("&gt;", ">");
        _gridView.Rows[_rowIndex].Cells[_cells].Text = _gridView.Rows[_rowIndex].Cells[_cells].Text.Replace(",", "<br>");


    }

    /// <summary>
    /// 绑定GridView
    /// </summary>
    /// <author>grokyao</author>
    /// <date>2009-2-23</date>
    void bindQuarterPlan()
    {
        object[] _value = new object[2];        
        _value[0] = this.drpDepartment.SelectedItem.Text;
        _value[1] = Convert.ToInt32(this.drpQuarterDate.SelectedItem.Value);
        DataTable _quareterPlan = dllQuarterPlanofManager.get(QuarterPlanofManager.field.Sponsor.ToString(), QuarterPlanofManager.field.MasterDepartment.ToString(), QuarterPlanofManager.field.QuarterDate.ToString(), "1", _value);
        DataView dv = new DataView(_quareterPlan);
        dv.Sort = "QuarterPlanSortId";
        this.gdvQuarterPlan.DataSource = dv;
        this.gdvQuarterPlan.DataBind();
        for (int i = 0; i < this.gdvQuarterPlan.Rows.Count; i++)
        {
            LinkButton lbtn = (LinkButton)gdvQuarterPlan.Rows[i].Cells[4].FindControl("lbtnSource");
            lbtn.Text = gdvQuarterPlan.DataKeys[i]["Source"].ToString();
            //文件下载，判断如果下载了就显示《下载按钮》 反之 就显示“无附件”
            if (this.gdvQuarterPlan.DataKeys[i]["AttachmentPath"].ToString().Length == 0)
            {
                Button _btn = (Button)this.gdvQuarterPlan.Rows[i].Cells[13].FindControl("btnDownLoad");
                _btn.Visible = false;
                Label _lbl = (Label)this.gdvQuarterPlan.Rows[i].Cells[13].FindControl("lblAlert");
                _lbl.Visible = true;
                _lbl.Text = "无附件";
            }
            object[] _valueQuarterPlanResolve = new object[1];
            _valueQuarterPlanResolve[0] = this.gdvQuarterPlan.DataKeys[i]["QuarterPlanId"].ToString();
            DataTable _quarterResolve = dllQuarterPlanDetail.get(QuarterPlanDetailManager.field.QuarterPlanId.ToString(), _valueQuarterPlanResolve);
            if (_quarterResolve.Rows.Count > 0)
            {
                Button btn = (Button)this.gdvQuarterPlan.Rows[i].Cells[13].FindControl("btnQuarterPlanResolve");
                Label lbl = (Label)this.gdvQuarterPlan.Rows[i].Cells[13].FindControl("lblTopic");
                btn.Visible = true;
                lbl.Visible = false;
            }
            else
            {
                Button btn = (Button)this.gdvQuarterPlan.Rows[i].Cells[13].FindControl("btnQuarterPlanResolve");
                Label lbl = (Label)this.gdvQuarterPlan.Rows[i].Cells[13].FindControl("lblTopic");
                btn.Visible = false;
                lbl.Visible = true;
            }
            wrapByComma(this.gdvQuarterPlan, i, 7);
            wrapByComma(this.gdvQuarterPlan, i, 8);

            this.gdvQuarterPlan.Rows[i].Cells[12].Text = this.gdvQuarterPlan.Rows[i].Cells[11].Text.Replace("&", "");
            this.gdvQuarterPlan.Rows[i].Cells[12].Text = this.gdvQuarterPlan.Rows[i].Cells[11].Text.Replace("nbsp;", "");
            this.gdvQuarterPlan.Rows[i].Cells[12].Text = this.gdvQuarterPlan.Rows[i].Cells[11].Text.Replace("amp;", "");
        }
    }

    /// <summary>
    /// 绑定DropDownList
    /// </summary>
    /// <author>grokyao</author>
    /// <date>2009-2-16</date>
    void bindDropDownList(DropDownList _drp)
    {
        if (_drp.Equals(this.drpDepartment))
        {
            object[] _value = new object[1];
            Model.UserInfo objUserInfo = new Model.UserInfo();
            _value[0] = objUserInfo.UserName;
            DataTable _userTable = dllUserInfo.get(UserInfoManager.field.UserName.ToString(), _value);
            if (_userTable.Rows.Count > 0)
            {
                if (_userTable.Rows[0]["DepartmentId"].ToString().Length > 0)
                {
                    ListItem _li = new ListItem(_userTable.Rows[0]["DepartmentId"].ToString());
                    this.drpDepartment.Items.Add(_li);
                }
                if (_userTable.Rows[0]["PartTimeDepartmentId"].ToString().Length > 0)
                {
                    ListItem _li = new ListItem(_userTable.Rows[0]["PartTimeDepartmentId"].ToString());
                    this.drpDepartment.Items.Add(_li);
                }
            }
        }
        if (_drp.Equals(this.drpYear))
        {
            for (int i = 2009; i < 2100; i++)
            {
                ListItem li = new ListItem(i.ToString(), i.ToString());
                _drp.Items.Add(li);
            }
            //根据系统日期自动绑定到当前年份
            //string _year = DateTime.Now.Year.ToString();
            //this.drpYear.SelectedIndex = this.drpYear.Items.IndexOf(this.drpYear.Items.FindByText(_year));
            //根据系统当前日期查找到对应的年周期
            DataTable _year = dllQuarterDateManager.getQuarterDate();
            this.drpYear.SelectedIndex = this.drpYear.Items.IndexOf(this.drpYear.Items.FindByText(_year.Rows[0][2].ToString()));

        }
        if (_drp.Equals(this.drpQuarterDate))
        {
            object[] _value = new object[1];
            _value[0] = this.drpYear.SelectedValue;
            DataTable _quarter = dllQuarterDateManager.get(QuarterDateManager.field.QuarterYear.ToString(), _value);
            if (_quarter.Rows.Count != 0)
            {
                this.drpQuarterDate.DataSource = _quarter;
                this.drpQuarterDate.DataTextField = "QuarterName";
                this.drpQuarterDate.DataValueField = "Quarter_Id";
                this.drpQuarterDate.DataBind();
                #region dropdownlist显示系统所对应的当前年周期
                //根据系统当前日期查找到对应的年周期
                DataTable _quartertime = dllQuarterDateManager.getQuarterDate();
                //如果查到结果（结果只有一条）

                if (_quartertime.Rows.Count == 1)
                {
                    this.drpQuarterDate.SelectedIndex = this.drpQuarterDate.Items.IndexOf(this.drpQuarterDate.Items.FindByText(_quartertime.Rows[0][1].ToString()));
                    this.drpQuarterDate.DataSource = _quartertime;
                    this.drpQuarterDate.DataTextField = "QuarterName";
                    this.drpQuarterDate.DataValueField = "Quarter_Id";
                }
                #endregion
                bindQuarterPlan();
            }
            else
            {
                ListItem li = new ListItem("无年周期");
                this.drpQuarterDate.Items.Clear();
                this.drpQuarterDate.Items.Add(li);
                this.gdvQuarterPlan.DataSource = new DataTable();
                this.gdvQuarterPlan.DataBind();
            }
           
        }
    }

    /// <summary>
    /// 自动分页事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <author>grokyao</author>
    /// <date>2009-2-23</date>
    protected void gdvQuarterPlan_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.gdvQuarterPlan.PageIndex = e.NewPageIndex;
        bindQuarterPlan();
    }

    /// <summary>
    /// 年周期改变事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <author>grokyao</author>
    /// <date>2009-2-24</date>
    protected void drpQuarterDate_SelectedIndexChanged(object sender, EventArgs e)
    {
        ListItem _li = this.drpQuarterDate.SelectedItem;
        if (_li != null)
        {
            if (_li.Text == "无年周期")
            {
                this.gdvQuarterPlan.DataSource = new DataTable();
                this.gdvQuarterPlan.DataBind();
            }
            else
            {
                bindQuarterPlan();
            }
        }
    }


    /// <summary>
    /// 根据年计划id查看当前流程审批位置
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <author>grokyao</author>
    /// <date>2009-2-24</date>
    protected void btnVerifyCircuit_Click(object sender, EventArgs e)
    {
        int _count = 0;
        string _url = "";
        int _quarterPlanId = 0;
        for (int i = 0; i < this.gdvQuarterPlan.Rows.Count; i++)
        {
            CheckBox ckb = (CheckBox)this.gdvQuarterPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (ckb.Checked == true)
            {
                _count++;
                _quarterPlanId = Convert.ToInt32(this.gdvQuarterPlan.DataKeys[i]["QuarterPlanId"].ToString());
            }
        }
        if (_count > 1)
        {
            Utility.HttpHelp.alert("只能选择一个计划", Page);
            return;
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请选择一个计划", Page);
            return;
        }
        _url = "../WebCommon/VerifyCircruitDisplay.aspx?PlanId=" + _quarterPlanId + "&PlanType=1";
        Page.RegisterStartupScript("windowOpen",
           "<script language=javascript>window.open('" + _url + "','newwindow','height=150,width=550,top=250,left=300,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");
    }


    /// <summary>
    /// 撤回按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <author>grokyao</author>
    /// <date>2009-2-26</date>
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        int _count = 0;
        List<object[]> _valueList = new List<object[]>();
        string  _alert = "";
        for (int i = 0; i < this.gdvQuarterPlan.Rows.Count; i++)
        {
            CheckBox ckb = (CheckBox)this.gdvQuarterPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (ckb.Checked == true)
            {
                _count++;
                //根据年计划id，查询计划在流程审核的位置
                object[] _value = new object[1];
                _value[0] = Convert.ToInt32(this.gdvQuarterPlan.DataKeys[i]["QuarterPlanId"].ToString());
                int state = Convert.ToInt32(this.gdvQuarterPlan.DataKeys[i]["PlanSendState"].ToString());

               if (state < 3)
               {
                   _valueList.Add(_value);
               }
               else
               {
                   _alert += this.gdvQuarterPlan.DataKeys[i]["QuarterPlanSortId"].ToString() + ",";
               }
            }
        }        
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请至少选择一个计划", Page);
            return;
        }
        if (_valueList.Count > 0)
        {
            int result = dllQuarterPlanofManager.editWithTransaction(QuarterPlanofManager.field.Sponsor.ToString(), _valueList);
            if (result == 0)
            {
                Utility.Error.RedirectErrorPage("撤回计划未成功，请重试！");
            }
            else
            {
                Response.Redirect("SendedQuarterPlan.aspx");
            }
        }
        if (_alert.Length > 0)
        {
            Utility.HttpHelp.alert("计划编号为" + _alert + "的计划的年计划已经审核完毕不可撤回", Page);
        }


        //------------------------------------------------------------


        //string _alert = "";
        //int _count = 0;
        //List<object[]> _valueList = new List<object[]>();
        //for (int i = 0; i < this.gdvQuarterResolve.Rows.Count; i++)
        //{
        //    CheckBox ckb = (CheckBox)this.gdvQuarterResolve.Rows[i].Cells[0].FindControl("ckbSelect");
        //    if (ckb.Checked)
        //    {
        //        _count++;
        //        object[] _quarterPlanId = new object[1];
        //        _quarterPlanId[0] = Convert.ToInt32(this.gdvQuarterResolve.DataKeys[i]["QuarterPlanId"].ToString());
        //        DataTable _quarterPlanTable = dllQuarterPlan.get(QuarterPlanofManager.field.QuarterPlanId.ToString(), _quarterPlanId);
        //        if (_quarterPlanTable.Rows.Count > 0)
        //        {
        //            if (Convert.ToInt32(_quarterPlanTable.Rows[0]["PlanSendState"].ToString()) == 0)
        //            {
        //                object[] _value = new object[1];
        //                _value[0] = Convert.ToInt32(this.gdvQuarterResolve.DataKeys[i]["Id"].ToString());
        //                _valueList.Add(_value);
        //            }
        //            else
        //            {
        //                _alert += this.gdvQuarterResolve.Rows[i].Cells[1].Text + ",";
        //            }
        //        }
        //    }
        //}
        //if (_count == 0)
        //{
        //    Utility.HttpHelp.alert("请选择要删除的记录", Page);
        //}
        //if (_alert.Length > 0)
        //{
        //    _alert = _alert.Remove(_alert.Length - 1, 1);
        //}
        //if (_valueList.Count > 0)
        //{
        //    int result = dllQuarterPlanDetail.delWithTransaction(_valueList);
        //    if (result == 0)
        //    {
        //        Utility.Error.RedirectErrorPage("删除年分解计划未成功，请重试！");
        //    }
        //    else
        //    {
        //        Utility.HttpHelp.alert("序号为" + _alert + "的计划不可以删除，因为对应的年计划已经提交", Page);
        //        bindGridViewQuarterResolve();
        //    }
        //}
        //if (_alert.Length > 0)
        //{
        //    Utility.HttpHelp.alert("序号为" + _alert + "的计划不可以删除，因为对应的年计划已经提交", Page);
        //}


    }


    /// <summary>
    /// 年份改变绑定年周期
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// <author>grokyao</author>
    /// <date>2009-2-26</date>
    protected void drpYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindDropDownList(this.drpQuarterDate);
        if(this.drpQuarterDate.Text!="无年周期")
        {
            bindQuarterPlan();
        }
        else
        {
            this.gdvQuarterPlan.DataSource = new DataTable();
            this.gdvQuarterPlan.DataBind();
        }
    }


    /// <summary>
    /// 下载按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDownLoad_Click(object sender, EventArgs e)
    {
        int i = 0;
        Button btt = (Button)sender;//获得当前控件
        TableCell cell = (TableCell)btt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        i = iRow.RowIndex;//得到该行的索引
        //读取隐藏地址列
        string path = this.gdvQuarterPlan.DataKeys[i]["AttachmentPath"].ToString();
       // Response.Redirect("~/upload/" + path);

        FileDownload(path); 
        //Utility.HttpHelp.DownloadFile(path);
    }

    ///   <summary>   
    ///   文件下载   
    ///   </summary>   
    ///   <param   name="FullFileName"></param>   
    private void FileDownload(string strFileName)
    {
        
        FileInfo DownloadFile = new FileInfo(strFileName);
        if (!DownloadFile.Exists)
        {
            Utility.HttpHelp.alert("无附件,请与管理员联系", Page);
            return;
        
        }
        Response.Clear();
        Response.ClearHeaders();
        Response.Buffer = false;
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName.Substring(strFileName.LastIndexOf('\\') + 1), System.Text.Encoding.UTF8));
       // Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());

        Response.WriteFile(DownloadFile.FullName);
        Response.Flush();
        Response.End();

    }

    /// <summary>
    /// 上传文件按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnAttachmentPath_Click(object sender, EventArgs e)
    {
        string _quarterId = "";
        int _count = 0;
        for (int i = 0; i < this.gdvQuarterPlan.Rows.Count; i++)
        {
            CheckBox ckb = (CheckBox)this.gdvQuarterPlan.Rows[i].Cells[0].FindControl("ckbSelect");
            if (ckb.Checked == true)
            {
                _quarterId = this.gdvQuarterPlan.DataKeys[i]["QuarterPlanId"].ToString();
                _count++;
            }
        }
        if (_count == 1)
        {
            //定向到添加年附件路径页面
            string _url = "../WebCommon/SendAttachmentPath.aspx?PlanId=" + _quarterId + "&PlanType=1";
            Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "','quarterplandetailmodify','height=40,width=400,top=300,left=300,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');</script>");
        }
        if (_count > 1)
        {
            Utility.HttpHelp.alert("只能选择一个计划", Page);
            return;
        }
        if (_count == 0)
        {
            Utility.HttpHelp.alert("请选择一个计划", Page);
            return;
        }    
    }
    /// <summary>
    /// 分解按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnQuarterPlanResolve_Click(object sender, EventArgs e)
    {
        int i = 0;
        Button bt = (Button)sender;//获得当前控件
        TableCell cell = (TableCell)bt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        i = iRow.RowIndex;//得到该行的索引
        int _quarterPlanId = Convert.ToInt32(this.gdvQuarterPlan.DataKeys[i]["QuarterPlanId"].ToString());
        string _url = "QuarterPlanResolveDetail.aspx?_quarterPlanId=" + _quarterPlanId;
        Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "','quarterPlandetail','height=200,width=900,top=300,left=80,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");

   }

    /// <summary>
    /// 部门改变事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpDepartment_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindQuarterPlan();
    }



    /// <summary>
    /// 来源事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lbtnSource_Click(object sender, EventArgs e)
    {
        int i = 0;
        LinkButton bt = (LinkButton)sender;//获得当前控件
        TableCell cell = (TableCell)bt.Parent;//得到所处的父单元格
        GridViewRow iRow = (GridViewRow)cell.Parent;//得到所处父单元行
        i = iRow.RowIndex;//得到该行的索引
        Control c = (Control)iRow.Parent;
        GridView _gdv = (GridView)c.Parent;

        int TotalPlanId = Convert.ToInt32(_gdv.DataKeys[i]["TotalPlanId"].ToString());
        if (TotalPlanId == 0)
        {
            //新增的月计划，不需要跳转到指定页面
        }
        else
        {
            string _url = "TotalPlanDetail.aspx?TotalPlanId=" + TotalPlanId;
            Page.RegisterStartupScript("windowsopen", "<script language=javascript>window.open('" + _url + "','newwindow','height=200,width=900,top=200,left=50,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no');</script>");
        }
    }
}
